package com.zhangxiaofanfan.hotcode.third;

import java.util.Arrays;

/**
 * <a href="https://leetcode.cn/problems/rotate-image/description/?envType=study-plan-v2&envId=top-100-liked">旋转图像</a>
 *
 * @author zhangxiaofanfan
 * @date 2024-05-27 20:56:12
 */
public class HotCode020 {
    public static void main(String[] args) {
        HotCode020 hotCode020 = new HotCode020();
        int[][] matrix = {
                {5,1,9,11},
                {2,4,8,10},
                {13,3,6,7},
                {15,14,12,16}
        };
        Arrays.stream(matrix).forEach(array -> System.out.println(Arrays.toString(array)));
        hotCode020.rotate(matrix);
        System.out.println("---------------");
        Arrays.stream(matrix).forEach(array -> System.out.println(Arrays.toString(array)));
    }

    public void rotate(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix.length != matrix[0].length) {
            throw new IllegalArgumentException("Invalid input");
        }
        rotateOneLayer(matrix, 0, matrix.length - 1, 0, matrix.length - 1);
    }

    public void rotateOneLayer(int[][] matrix, int left, int right, int top, int bottom) {
        if (left >= right || top >= bottom) {
            return ;
        }
        for (int i = 0, temp; i < right - left; i++) {
            temp = matrix[top][left + i];
            matrix[top][left + i] = matrix[bottom - i][left];
            matrix[bottom - i][left] = matrix[bottom][right - i];
            matrix[bottom][right - i] = matrix[top + i][right];
            matrix[top + i][right] = temp;
        }
        rotateOneLayer(matrix, left + 1, right - 1, top + 1, bottom - 1);
    }
}
